<template>
  <div>
    <div class="contract" v-if="!contractAddShow">
      <!-- 筛选按钮 -->
      <div class="search-button">
        <el-button
          v-hasPermi="['system:contract:query']"
          class="btn search"
          @click="getContractList"
          ><el-icon class="icon" color="#fff"> <Search /> </el-icon
          >查询</el-button
        >
        <el-button
          v-hasPermi="['system:contract:add']"
          class="btn search"
          @click="
            contractAddShow = true;
            pageType = 'add';
          "
          ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
          >新增</el-button
        >
        <el-button class="btn add" @click="handleRefresh"
          ><el-icon class="icon" color="#fff"> <Refresh /> </el-icon
          >重置</el-button
        >
        <el-popover :width="170" trigger="click" placement="bottom">
          <template #reference>
            <el-button class="btn search" style="width: 100px"
              ><el-icon class="icon" color="#fff"> <Setting /> </el-icon
              >显示列</el-button
            >
          </template>
          <el-checkbox-group v-model="checkList" @change="handleCheckChange">
            <div>
              <el-checkbox label="templateTypeName">模板类型</el-checkbox>
            </div>
            <div>
              <el-checkbox label="templateName">合同模板名称</el-checkbox>
            </div>
            <div>
              <el-checkbox label="createTime">上传时间</el-checkbox>
            </div>
            <div>
              <el-checkbox label="uploadMan">上传人</el-checkbox>
            </div>
          </el-checkbox-group>
        </el-popover>
      </div>
      <!-- 筛选条件 -->
      <div class="search">
        <div class="search-item">
          <el-input
            clearable
            v-model.trim="params.templateName"
            class="search-input"
            maxlength="30"
            placeholder="请输入合同模板名称"
          ></el-input>
        </div>
        <div class="search-item">
          <el-select
            v-model="params.templateType"
            placeholder="请选择模板类型"
            clearable
            class="search-input"
          >
            <el-option
              v-for="dict in templateList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </div>
      </div>

      <!-- 表格数据 -->
      <el-table
        v-loading="loading"
        :data="contractList"
        border
        height="64vh"
        :header-cell-style="{ 'text-align': 'center' }"
        @sort-change="sortChange"
      >
        <!-- 操作模式 -->
        <el-table-column
          label="操作"
          :show-overflow-tooltip="true"
          width="140px"
        >
          <template #default="{ row }">
            <div class="table-operate">
              <el-icon
                v-hasPermi="['system:contract:detail']"
                title="查看详情"
                color="#007CEF"
                class="table-icon"
                :size="20"
                @click="handleOperate('detail', row)"
              >
                <Document />
              </el-icon>
              <el-icon
                v-hasPermi="['system:contract:down']"
                title="下载"
                color="#007CEF"
                class="table-icon"
                :size="20"
                @click="fileDown(row)"
              >
                <Download />
              </el-icon>
              <el-icon
                v-hasPermi="['system:contract:remove']"
                title="删除"
                color="#E33838"
                class="table-icon"
                :size="20"
                @click="handleOperate('delete', row)"
              >
                <Delete />
              </el-icon>
            </div> </template
        ></el-table-column>
        <el-table-column
          type="index"
          label="序号"
          :index="indexMethod"
          width="70"
          align="center"
        />
        <el-table-column
          v-if="checkList.includes('templateTypeName')"
          label="模板类型 "
          prop="templateTypeName"
          :show-overflow-tooltip="true"
          min-width="80"
          sortable="custom"
        />
        <el-table-column
          v-if="checkList.includes('templateName')"
          label="合同模板名称"
          prop="templateName"
          :show-overflow-tooltip="true"
          min-width="80"
          sortable="custom"
        />
        <el-table-column
          v-if="checkList.includes('createTime')"
          label="上传时间"
          prop="createTime"
          :show-overflow-tooltip="true"
          min-width="80"
          sortable="custom"
        />
        <el-table-column
          v-if="checkList.includes('uploadMan')"
          label="上传人"
          prop="uploadMan"
          :show-overflow-tooltip="true"
          min-width="80"
          sortable="custom"
        />
      </el-table>

      <!-- 分页 -->
      <pagination
        class="pagination"
        :total="total"
        v-model:page="params.pageNum"
        v-model:limit="params.pageSize"
        @pagination="getContractList"
      />
    </div>
    <ContractAdd
      v-if="contractAddShow"
      ref="contractAddRef"
      v-model:contractAddShow="contractAddShow"
      @refreshList="getContractList"
      :pageType="pageType"
    />
  </div>
</template>

<script setup>
import ContractAdd from "./contractAdd";
import { getDictsApi, fileDownload } from "@/api/dict";
import { Base64 } from "js-base64";
import {
  getContractListApi,
  deleteContractApi,
} from "@/api/information/contract";
import { addTableHeaderApi, getTableHeaderApi } from "@/api/pub";
import { ElMessage, ElMessageBox } from "element-plus";
import useUserStore from "@/store/modules/user";
//当前用户信息
const userStore = useUserStore();
// 搜索参数
const params = reactive({
  templateName: "",
  templateType: null,
  pageNum: 1,
  pageSize: 50,
  sortField: "",
  sortOrder: "",
});

const checkList = ref([
  "templateTypeName",
  "templateName",
  "createTime",
  "uploadMan",
]);

// 表格加载效果
const loading = ref(false);
// 合同模板新增组件显隐
const contractAddShow = ref(false);
// 合同模板列表
const contractList = ref([]);
// 合同模板新增组件引用
const contractAddRef = ref(null);
// 操作类型
const pageType = ref("");
// 模板列表
const templateList = ref([]);
// 总数
const total = ref(0);

/**
 * @description: 复选框选中
 */
const handleCheckChange = async (val) => {
  var str = val.join(",");
  const result = await addTableHeaderApi({
    moduleType: 2,
    titleField: str,
  });
};

/**
 * @description: 获取表头
 */
const getTableHeader = async () => {
  const result = await getTableHeaderApi({
    moduleType: 2,
  });
  if (result.code == 200) {
    var arr = result.data.titleField.split(",");
    checkList.value = arr;
  }
};

/**
 * @description: 获取合同模板列表
 */
const getContractList = async () => {
  try {
    loading.value = true;
    let {
      templateName,
      templateType,
      pageNum,
      pageSize,
      sortField,
      sortOrder,
    } = params;
    const res = await getContractListApi(
      { pageNum, pageSize },
      {
        templateName,
        templateType,
        sortField,
        sortOrder,
      }
    );
    contractList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  } catch {
    loading.value = false;
  }
};

/**
 * @description: 列表排序
 * @param {*} column.prop //当前排序取的字段
 * @param {*} column.order // "desc" "asc" 正序或倒序
 */
const sortChange = (column) => {
  params.sortField = column.prop;
  if (column.order === "descending") {
    params.sortOrder = "DESC"; // 排序或倒序
  } else {
    params.sortOrder = "ASC"; // 排序或倒序
  }
  getContractList();
};

/**
 * @description: 重置
 */
const handleRefresh = () => {
  Object.assign(params, {
    templateName: "",
    templateType: null,
    pageNum: 1,
    pageSize: 50,
    sortField: "",
    sortOrder: "",
  });
  getContractList();
};

/**
 * @description: 表格操作
 * @param {String} type 类型
 * @param {Object} row  当前行数据
 */
const handleOperate = async (type, row) => {
  switch (type) {
    case "detail":
      let docUrl = row.url;
      let url = encodeURIComponent(Base64.encode(docUrl));
      let officeUrl =
        "http://101.71.158.60:50098/onlinePreview?url=" +
        url +
        "&watermarkTxt=" +
        encodeURIComponent(userStore.nickName); // 在新窗口打开编码后的链接
      window.open(officeUrl, "_target");
      break;
    case "delete":
      ElMessageBox.confirm("此操作将删除该合同模板，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
        type: "warning",
      })
        .then(async () => {
          const res = await deleteContractApi(row.templateId);
          if (res.code === 200) {
            ElMessage.success(res.msg);
            getContractList();
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
      break;

    default:
      break;
  }
};

/**
 * @description: 文件下载
 * @param {Object} row  当前行数据
 */
const fileDown = (row) => {
  // const res = fileDownload(row.url);
  // var debug = res;
  // if (debug) {
  // 创建隐藏的可下载链接  //url下载
  if (row.url) {
    let eleLink = document.createElement("a");
    eleLink.download = row.name;
    eleLink.style.display = "none";
    eleLink.href = row.url;
    // 触发点击
    document.body.appendChild(eleLink);
    eleLink.click();
    // 然后移除
    document.body.removeChild(eleLink);
  }

  // var elink = document.createElement("a");
  // console.log("row.name", row.name);
  // elink.download = row.name;
  // elink.style.display = "none";
  // var blob = new Blob([debug], { type: "application/octet-stream" });
  // elink.href = URL.createObjectURL(blob);
  // document.body.appendChild(elink);
  // elink.click();
  // document.body.removeChild(elink);
  // } else {
  //   this.$message.error($t("common.DownloadException"));
  // }
};

/**
 * @description: 获取字典
 */
async function getDicts() {
  // 模板列表
  await getDictsApi("contract_template_type").then((res) => {
    if (res.code === 200) {
      templateList.value = res.data;
    }
  });
}

/**
 * @description: 序号
 * @param {Number} index 索引
 */
function indexMethod(index) {
  const currentPage = params.pageNum;
  const pageSize = params.pageSize;
  const truelndex = (currentPage - 1) * pageSize + index + 1;
  return truelndex;
}

onMounted(() => {
  getTableHeader();
  getContractList();
  getDicts();
});
</script>
<style>
@import "@/assets/styles/confirmBtn.css";
</style>
<style lang="scss" scoped>
.contract {
  padding: 20px;
  width: 100%;
  height: 100%;
  .pagination {
    margin-top: 20px;
  }
}
</style>
